package com.primal.quartz.config;

import org.quartz.Trigger;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * Author whh
 * Date 2023/10/11/ 21:44
 * <p></p>
 */
@ImportResource(value = {
        "classpath:configJobs/*ApplicationContext.xml"
})
@Configuration
public class QuartzConfig implements ApplicationContextAware {



    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(AutowireCapableBeanFactory capableBeanFactory,ApplicationContext ctx){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setConfigLocation(new ClassPathResource("quartz.properties"));
        schedulerFactoryBean.setJobFactory(new AdaptableJobFactory(){
            @Override
            protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
                Object jobInstance = super.createJobInstance(bundle);
                capableBeanFactory.autowireBean(jobInstance);
                return jobInstance;
            }
        });

        //设置触发器
        schedulerFactoryBean.setTriggers(ctx.getBeansOfType(CronTriggerFactoryBean.class).values().stream().map(CronTriggerFactoryBean::getObject).toArray(Trigger[]::new));
        schedulerFactoryBean.setAutoStartup(true);
        return schedulerFactoryBean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContext parent = applicationContext.getParent();
        if(parent != null){
            System.out.println("refresh2");
        }else {
            System.out.println("refresh1");
        }

    }
}
